<?php

namespace app;

use think\db\concern\JoinAndViewQuery;
use think\facade\Db;
use think\Model;

/**
 * 基础公用模型
 */
class BaseModel extends Model
{
    use JoinAndViewQuery;

    /**
     * 获取单条数据
     * @param array $where
     * @param string $field
     * @param array|string $order
     * @return array
     */
    public static function findOne(array $where, string $field = '*', array|string $order = []): array
    {
        $data = self::field($field)->where($where)->order($order)->find();
        $data = $data ? $data->toArray() : [];
        return $data;
    }

    /**
     * 删除
     * @param array $where
     * @param bool $bool
     * @return Model|bool
     */
    public static function deleteData(array $where, bool $bool = false): Model|bool
    {
        if ($bool) {
            $res = self::where($where)->delete();
        } else {
            $res = self::where($where)->update(['closed' => 1, 'update_time' => time()]);
        }
        return $res;
    }

    /**
     * 设置排序值
     * @param Model $model
     * @param array $where
     * @param int $orderby
     * @return int
     */
    public static function setOrderBy(Model $model, array $where = [], int $orderby = 0): int
    {
        //默认条件
        $where2[] = ['orderby', '>=', $orderby];
        $where2[] = ['closed', '=', 0];
        //判断是否存在$orderby
        if ($orderby !== 0) {
            //获取比当前大的所有值
            $list = $model::where($where)->where($where2)->order('orderby asc')->column('id,orderby');
            foreach ($list as &$v) {
                if ($model['id'] != $v['id']) {
                    $orderby += 1;
                }
                $v['orderby'] = $orderby;
            }
            $model->saveAll($list);
        } else {
            //不存在$orderby
            $orderby = $model::where($where)->where($where2)->order('orderby desc')->value('orderby');
            $orderby += 1;
        }
        return $orderby;
    }

    /**
     * 开启事务
     */
    public static function startTrans()
    {
        Db::startTrans();
    }

    /**
     * 提交事务
     */
    public static function commit()
    {
        Db::commit();
    }

    /**
     * 关闭事务
     */
    public static function rollback()
    {
        Db::rollback();
    }

    /**
     * 随机排序
     * @access public
     * @return $this
     */
    public function orderRand()
    {
        $this->options['order'][] = '[rand]';
        return $this;
    }


}


